//
//  AdressViewController.m
//  Contractor
//
//  Created by 金鑫 on 16/5/26.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "AdressViewController.h"
#import "LocationViewController.h"
#import "reviseViewController.h"
#import "CONST.h"
#import "MBProgressHUD.h"

@interface AdressViewController ()<UITextViewDelegate>
{
    UIView *buttomBackview ;
    UITextView *locationtextView ;
    UIScrollView *scrollView ;
    UILabel *locationLabel ;
    NSMutableArray *allArray ;
    NSMutableArray *provinceArray ;
    NSMutableArray *cityArray ;
    NSMutableArray *districtArray ;
}

@end

@implementation AdressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO ;
    self.navigationItem.title = @"修改所在地" ;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
    self.view.backgroundColor = [UIColor whiteColor] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    
    NSData *data = [NSData dataWithData:[uidDefaults valueForKey:@"LocationArray"]] ;
    NSArray *array =  [NSKeyedUnarchiver unarchiveObjectWithData:data] ;
    allArray = [NSMutableArray arrayWithArray:array] ;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self initprovinceArray] ;
//        _locationModel = [self modelwithProvince:_model.liveLocation1 city:_model.liveLocation2 district:_model.liveLocation3] ;
        [self createBackView] ;
    }) ;
}

//- (void)viewDidAppear:(BOOL)animated
//{
//    if (_locationModel) {
//        locationLabel.text = [NSString stringWithFormat:@"%@ %@ %@",_locationModel.location1_cn,_locationModel.location2_cn,_locationModel.location3_cn] ;
//    }
//}

- (void)createBackView
{
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, __kScreenWidth, self.view.frame.size.height)] ;
    scrollView.backgroundColor = [UIColor whiteColor] ;
    scrollView.showsVerticalScrollIndicator = NO ;
    [self.view addSubview:scrollView] ;
    
    //区域背景view
    UIView *locationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, __kScreenWidth, 60)] ;
    locationView.backgroundColor = [UIColor whiteColor] ;
    locationView.userInteractionEnabled = YES ;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer
                                                     alloc] initWithTarget:self action:@selector(pushAdress)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [locationView addGestureRecognizer: tapGestureRecognizer];
    
    [scrollView addSubview:locationView] ;
    
    //线1
    UIImageView *line1 = [self createline:CGRectMake(0, locationView.frame.origin.y + locationView.frame.size.height, __kScreenWidth, 1)] ;
    [scrollView addSubview:line1] ;
    
    //右箭头图片
    UIImageView *nextView = [[UIImageView alloc] initWithFrame:CGRectMake(__kScreenWidth-40, 12.5 , 25, 35)] ;
    [nextView setImage:[UIImage imageNamed:@"page_access_next_icon.png"]] ;
    [locationView addSubview:nextView] ;
    
    //NSString *locationStr = [NSString stringWithFormat:@"%@ %@ %@",_model.liveLocation1,_model.liveLocation2,_model.liveLocation3] ;
    
//    myLTmodel = [[LocationModel alloc] init] ;
    if (!_locationModel) {
        _locationModel = [self modelwithProvince:_model.liveLocation1 city:_model.liveLocation2 district:_model.liveLocation3] ;
    }
//    else{
//        myLTmodel = [self modelwithProvince:_model.liveLocation1 city:_model.liveLocation2 district:_model.liveLocation3] ;
//    }
    
    locationLabel = [self creatLabel:[NSString stringWithFormat:@"%@ %@ %@",_locationModel.location1_cn,_locationModel.location2_cn,_locationModel.location3_cn] frame:CGRectMake(30, 10, __kScreenWidth - 60, 22.0f) size:20.0f color:[UIColor blackColor]] ;
    
    [locationView addSubview:locationLabel] ;
    
    UILabel *liveNowLabel = [self creatLabel:@"所在区域" frame:CGRectMake(12,locationLabel.frame.origin.y + locationLabel.frame.size.height + 6,150,16.0f) size:14.0f color:[UIColor grayColor]] ;
    [locationView addSubview:liveNowLabel] ;
    
    locationtextView = [[UITextView alloc] initWithFrame:CGRectMake(24, line1.frame.origin.y + line1.frame.size.height , __kScreenWidth - 50, 30.0f)] ;
    locationtextView.text = _model.liveaddress ;
    locationtextView.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:20.0f] ;
    locationtextView.textAlignment = NSTextAlignmentLeft ;
    locationtextView.textColor = [UIColor blackColor] ;
    locationtextView.delegate = self ;
    [scrollView addSubview:locationtextView] ;
    
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
    [topView setBarStyle:UIBarStyleDefault];
    
    UIBarButtonItem * helloButton = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleBordered target:self action:nil];
    
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    btn.frame =CGRectMake(0, 0, 25, 35);
    
    btn.transform = CGAffineTransformMakeRotation(M_PI/2);
    
    [btn setBackgroundImage:[UIImage imageNamed:@"page_access_next_icon.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(dismissKeyBoard) forControlEvents:UIControlEventTouchUpInside] ;
    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithCustomView:btn] ;
    
    NSArray * buttonsArray = [NSArray arrayWithObjects:helloButton,btnSpace,doneButton,nil];
    
    [topView setItems:buttonsArray];
    [locationtextView setInputAccessoryView:topView];
    
    buttomBackview = [[UIView alloc] initWithFrame:CGRectMake(0, locationtextView.frame.origin.y + locationtextView.frame.size.height, __kScreenWidth, 400)] ;
    [scrollView addSubview:buttomBackview] ;
    UILabel *detailLocationLabel = [self creatLabel:@"详细街道地址" frame:CGRectMake(12, 6, 150, 16.0f) size:14.0f color:[UIColor grayColor]] ;
    [buttomBackview addSubview:detailLocationLabel] ;
    
    UIImageView *line2 = [self createline:CGRectMake(0, detailLocationLabel.frame.origin.y + detailLocationLabel.frame.size.height + 10, __kScreenWidth, 1)] ;
    [buttomBackview addSubview:line2] ;
    
    UILabel *nameLabel = [self creatLabel:_model.realname frame:CGRectMake(30, line2.frame.origin.y + line2.frame.size.height + 10, 150, 22.0f) size:20.0f color:[UIColor blackColor]] ;
    [buttomBackview addSubview:nameLabel] ;
    
    UILabel *mynameLable = [self creatLabel:@"我的名字" frame:CGRectMake(12, nameLabel.frame.origin.y + nameLabel.frame.size.height + 6, 150, 16.0f) size:14.0f color:[UIColor grayColor]] ;
    [buttomBackview addSubview:mynameLable] ;
    
    UIImageView *line3 = [self createline:CGRectMake(0, line2.frame.origin.y + line2.frame.size.height + 60, __kScreenWidth, 1)] ;
    [buttomBackview addSubview:line3] ;
    
    CGSize phonenumLength = [self lengthwithLabel:_model.nickname withsize:20.0f] ;
    
    UILabel *phoneNumLabel = [self creatLabel:_model.nickname frame:CGRectMake(30, line3.frame.origin.y + line3.frame.size.height + 10, phonenumLength.width, 22.0f) size:20.0f color:[UIColor blackColor]] ;
    [buttomBackview addSubview:phoneNumLabel] ;
    
    UILabel *myNumLabel = [self creatLabel:@"联系电话" frame:CGRectMake(12, phoneNumLabel.frame.origin.y + phoneNumLabel.frame.size.height + 6, 150, 16.0f) size:14.0f color:[UIColor grayColor]] ;
    [buttomBackview addSubview:myNumLabel] ;
    
    UIImageView *line4 = [self createline:CGRectMake(0, line3.frame.origin.y + line3.frame.size.height + 60, __kScreenWidth, 1)] ;
    [buttomBackview addSubview:line4] ;
    
    UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(20,line4.frame.origin.y + line4.frame.size.height + 30, __kScreenWidth - 40,50)] ;
    [saveBtn setTitle:@"保存修改" forState:UIControlStateNormal] ;
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    saveBtn.backgroundColor = [UIColor blueColor] ;
    saveBtn.layer.cornerRadius = 5.0f ;
    [saveBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside] ;
    [buttomBackview addSubview:saveBtn] ;
}

- (void)save
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = NSLocalizedString(@"正在努力加载", @"HUD loading title") ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:216] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    
    /*
     "idcard": "20150720000009000012",        //身份证
     "gender":1,                                //性别 1=男  2=女
     "realname":"太上老君",                        //姓名
     "liveLocation1":"AH",                        //居住地域
     "liveLocation2":"00",
     "liveLocation3":"00",
     "serviceLocate1":"BJ",                        //服务地域
     "serviceLocate2":"00",
     "serviceLocate3":"00",
     "liveaddress":"北京市东城区天坛东路甲1号天坛公园内" //居住地址
     */
    
    NSDictionary *jsondic = @{@"liveLocation1":_locationModel.location1,
                              @"liveLocation2":_locationModel.location2,
                              @"liveLocation3":_locationModel.location3,
                              @"liveaddress":locationtextView.text} ;
    NSLog(@"%@",jsondic) ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    NSLog(@"%@",jsondic) ;
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    
    NSLog(@"parameters:%@",parameters) ;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [hud hideAnimated:YES] ;
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             NSLog(@"通知:%@",dic) ;
             if ([dic[@"status"]integerValue] == 1) {
                 reviseViewController *vc = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2];
                 
                 vc.addressStr = [NSString stringWithFormat:@"%@ %@ %@ %@",_locationModel.location1_cn,_locationModel.location2_cn,_locationModel.location3_cn,locationtextView.text] ;
                 
                 [self.navigationController popToViewController:vc animated:NO];
             }
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [hud hideAnimated:YES] ;
         NSLog(@"Error: %@", error);
     }];

}

- (void)dismissKeyBoard
{
    [locationtextView resignFirstResponder] ;
}

- (void)textViewDidChange:(UITextView *)textView
{
    CGRect frame = textView.frame ;
    frame.size.height = textView.contentSize.height ;
    textView.frame = frame ;
    NSLog(@"%f",frame.size.height) ;
//    [textView removeFromSuperview] ;
//    [self.view addSubview:textView] ;
    [UIView animateWithDuration:0.2 animations:^{
        buttomBackview.frame = CGRectMake(0, textView.frame.origin.y + textView.frame.size.height, __kScreenWidth, 400) ;
        scrollView.contentSize = CGSizeMake(0, buttomBackview.frame.origin.y + buttomBackview.frame.size.height) ;
    }];
    
}

- (void)pushAdress
{
    LocationViewController *vc = [[LocationViewController alloc] init] ;
    vc.superModel = _model ;
    vc.myModel = _locationModel ;
    self.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:vc animated:NO] ;
}



- (UIImageView *)createline:(CGRect)frame
{
    UIImageView *line = [[UIImageView alloc] initWithFrame:frame] ;
    [line setImage:[UIImage imageNamed:@"layout_small_line_bg.png"]] ;
    return line ;
}


- (UILabel *)creatLabel:(NSString *)titile frame:(CGRect )frame size:(CGFloat)size color:(UIColor *)color
{
    UILabel *Label = [[UILabel alloc] init] ;
    Label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:size] ;
    Label.backgroundColor = [UIColor clearColor] ;
    Label.text = titile ;
    Label.textAlignment = NSTextAlignmentLeft ;
    Label.textColor = color ;
    Label.frame = frame ;
    return Label ;
}

- (CGSize)lengthwithLabel:(NSString *)lable withsize:(CGFloat) size
{
    NSDictionary *attribute1 = @{NSFontAttributeName: [UIFont fontWithName:@"AvenirLTStd-Light" size:size]};
    CGSize DescSize = [lable boundingRectWithSize:CGSizeMake(MAXFLOAT, size) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute1 context:nil].size;
    return DescSize ;
}

#pragma mark - 取地址
- (void)initprovinceArray
{
    provinceArray = [NSMutableArray array] ;
    for (NSInteger i = 0; i < allArray.count; i++) {
        LocationModel *model = [[LocationModel alloc] init] ;
        model = allArray[i] ;
        if (provinceArray.count == 0) {
            [provinceArray addObject:model] ;
        }
        else if (provinceArray.count > 0) {
            LocationModel *provinceModel = [provinceArray lastObject] ;
            if (![model.location1 isEqualToString:provinceModel.location1]) {
                [provinceArray addObject:model] ;
            }
        }
    }
    NSLog(@"省份：%lu",(unsigned long)provinceArray.count) ;
    for (LocationModel *provinceModel in provinceArray) {
        NSLog(@"%@",provinceModel.location1_cn) ;
    }
    //    LocationModel *model = [[LocationModel alloc] init] ;
    //    model = provinceArray[1] ;
    //    [self initCityArray:model.location1] ;
}

- (void)initCityArray:(NSString *)province
{
    cityArray = [NSMutableArray array] ;
    [cityArray removeAllObjects] ;
    for (NSInteger i = 0; i < allArray.count; i++)
    {
        LocationModel *model = [[LocationModel alloc] init] ;
        model = allArray[i] ;
        if (cityArray.count == 0 && [model.location1_cn isEqualToString:province]) {
            [cityArray addObject:model] ;
        }
        if ([model.location1_cn isEqualToString:province] && cityArray.count > 0) {
            LocationModel *cityModel = [cityArray lastObject] ;
            if (![model.location2_cn isEqualToString:cityModel.location2_cn]) {
                [cityArray addObject:model] ;
            }
        }
    }
    NSLog(@"城市：%lu",(unsigned long)cityArray.count) ;
    for (LocationModel *cityModel in cityArray) {
        NSLog(@"%@---%@",cityModel.location1_cn,cityModel.location2_cn) ;
    }
    //    LocationModel *model = [[LocationModel alloc] init] ;
    //    model = cityArray[1] ;
    //    [self initdistrictArray:model.location1 city:model.location2] ;
}

- (void)initdistrictArray:(NSString *)province city:(NSString *)city
{
    districtArray = [NSMutableArray array] ;
    [districtArray removeAllObjects] ;
    for (NSInteger i = 0; i < allArray.count; i++)
    {
        LocationModel *model = [[LocationModel alloc] init] ;
        model = allArray[i] ;
        if (districtArray.count == 0 && [model.location1_cn isEqualToString:province] && [model.location2_cn isEqualToString:city]) {
            [districtArray addObject:model] ;
        }
        if (districtArray.count > 0 && [model.location1_cn isEqualToString:province] && [model.location2_cn isEqualToString:city]) {
            LocationModel *districtModel = [districtArray lastObject] ;
            if (![model.location3_cn isEqualToString:districtModel.location3_cn]) {
                [districtArray addObject:model] ;
            }
        }
        
    }
    
    for (LocationModel *districtModel in districtArray) {
        NSLog(@"%@---%@---%@",districtModel.location1_cn,districtModel.location2_cn,districtModel.location3_cn) ;
    }
    
}

- (LocationModel *)modelwithProvince:(NSString *)province city:(NSString *)city district:(NSString *)district
{
    [self initCityArray:province] ;
    [self initdistrictArray:province city:city] ;
    
    NSMutableArray *modelArray = [NSMutableArray array] ;
    for (LocationModel *model in districtArray) {
        if ([model.location1_cn isEqualToString:province] && [model.location2_cn isEqualToString:city] && [model.location3_cn isEqualToString:district]) {
            [modelArray addObject:model] ;
        }
    }
    
    return modelArray[0] ;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
